<?php

namespace apiend\modules\statistic\models;

use Yii;
use common\helpers\ArrayHelper;
use common\helpers\ColorHelper;

/**
 * 概况统计面板
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class OverviewStatsChartModel extends OverviewStatsModel {

    /**
     * @var array 
     */
    private $_groupDefaults = [];

    /**
     * @var string
     */
    private $_dateFormat = '%Y-%m-%d';

    /**
     * {@inheritdoc}
     */
    public function afterValidate() {
        parent::afterValidate();
        $duration = $this->duration;
        $step = 86400;
        if ($duration <= 86400) {
            $this->_dateFormat .= ' %H:00';
            $step = 3600;
        }
//        elseif ($duration < 86400 * 31) {
//            $this->_dateFormat .= ' %p';
//            $step = 43200;
//        }
        $phpDateFormat = str_replace(['%', 'p'], ['', 'A'], $this->_dateFormat);
        $begin = $this->beginTime;
        $end = $this->endTime;
        $data = [];
        while ($begin < $end) {
            $data[] = date($phpDateFormat, $begin);
            $begin += $step;
        }
        $this->_groupDefaults = $data;
    }

    /**
     * {@inheritdoc}
     */
    public function getGroupDefaults() {
        return $this->_groupDefaults;
    }

    /**
     * {@inheritdoc}
     */
    public function getDateFormat() {
        return $this->_dateFormat;
    }

    /**
     * {@inheritdoc}
     */
    public function getItemStyle($color) {
        $rgbColor = ColorHelper::toRgba($color);
        if (empty($rgbColor)) {
            $rgbColor = [137, 189, 27];
        }
        $rgb = implode(',', $rgbColor);
        $colorOptions = [
            'color' => 'rgb(' . $rgb . ')',
            'borderColor' => 'rgba(' . $rgb . ', 0.27)',
            'borderWidth' => 8
        ];
        return $colorOptions;
    }

    /**
     * {@inheritdoc}
     */
    public function fillData($items) {
        $duration = $this->duration;
        if ($duration <= 3600) {
            return $items;
        }
        $mapItems = ArrayHelper::map($items, 'gtime', 'cnt');
        $data = [];
        foreach ($this->groupDefaults as $label) {
            $data[] = floatval(ArrayHelper::getValue($mapItems, $label, 0));
        }
        Yii::error($data);
        return $data;
    }

}
